﻿using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Imaging;

namespace SHomeWorkshop.LunarPresentation.Dialogs
{
    /// <summary>
    /// NewDocDialog.xaml 的交互逻辑
    /// </summary>
    public partial class NewDocDialog : Window
    {
        public NewDocDialog()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (Directory.Exists(Globals.pathOfUserTemplateDocuments))
            {
                string[] userTLibsubDirectories = Directory.GetDirectories(Globals.pathOfUserTemplateDocuments);

                if (userTLibsubDirectories.Length > 0)
                {
                    foreach (string s in userTLibsubDirectories)
                    {
                        tviUserTemplates.Items.Add(new TemplateDirItem(s));
                    }
                }
                else
                {
                    tviUserTemplates.Items.Add(new TreeViewItem() { Header = "..未找到模板子目录.." });
                }
            }
            else
            {
                tviUserTemplates.Items.Add(new TreeViewItem() { Header = "..未找到模板目录.." });
            }

            if (Directory.Exists(Globals.pathOfSystemTemplateDocuments))
            {
                string[] appTLibsubDirectories = Directory.GetDirectories(Globals.pathOfSystemTemplateDocuments);

                if (appTLibsubDirectories.Length > 0)
                {
                    foreach (string s in appTLibsubDirectories)
                    {
                        tviAppTemplates.Items.Add(new TemplateDirItem(s));
                    }
                }
                else
                {
                    tviAppTemplates.Items.Add(new TreeViewItem() { Header = "..未找到模板子目录.." });
                }
            }
            else
            {
                tviAppTemplates.Items.Add(new TreeViewItem() { Header = "..未找到模板目录.." });
            }

            tviDefFile.IsSelected = true;
            tvDirectiroy.Focus();
        }

        private void tvDirectiroy_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (listOfFile == null) return;//窗口建立过程中会引发此事件。因此可能尚未实例化。

            listOfFile.Items.Clear();
            previewImage.Source = null;

            if (tvDirectiroy.SelectedItem == tviDefFile)//建立默认文档。
            {
                listOfFile.IsEnabled = false;
                return;
            }
            else if (tvDirectiroy.SelectedItem == tviAppTemplates)//系统模板库。
            {
                listOfFile.IsEnabled = true;

                //读出系统模板
                if (Directory.Exists(Globals.pathOfSystemTemplateDocuments))
                {
                    string[] filenames = Directory.GetFiles(Globals.pathOfSystemTemplateDocuments);
                    if (filenames.Length > 0)
                    {
                        foreach (string s in filenames)
                        {
                            listOfFile.Items.Add(new TemplateListItem(s));
                        }
                    }
                }
            }
            else if (tvDirectiroy.SelectedItem == tviUserTemplates)//用户模板库。
            {
                listOfFile.IsEnabled = true;

                //读出用户自定义模板库
                if (Directory.Exists(Globals.pathOfUserTemplateDocuments))
                {
                    string[] filenames = Directory.GetFiles(Globals.pathOfUserTemplateDocuments);
                    if (filenames.Length > 0)
                    {
                        foreach (string s in filenames)
                        {
                            listOfFile.Items.Add(new TemplateListItem(s));
                        }
                    }
                }
                return;
            }
            else
            {
                listOfFile.IsEnabled = true;

                //读出各子类目录下的模板。
                TemplateDirItem tdi = tvDirectiroy.SelectedItem as TemplateDirItem;

                if (tdi != null && Directory.Exists(tdi.DirFullPath))
                {
                    string[] filenames = Directory.GetFiles(tdi.DirFullPath);
                    if (filenames.Length > 0)
                    {
                        foreach (string s in filenames)
                        {
                            listOfFile.Items.Add(new TemplateListItem(s));
                        }
                    }
                }
            }
        }

        private void btnNewFile_Click(object sender, RoutedEventArgs e)
        {
            if (tvDirectiroy.SelectedItem == tviDefFile)
            {
                this.Close();
                Commands.Command.NewDocument(Globals.MainWindow, Globals.MainWindow.mainTabControl);
                return;
            }

            TemplateListItem tli = listOfFile.SelectedItem as TemplateListItem;
            if (tli == null)
            {
                MessageBox.Show("请先选中一个模板！", Globals.appName,
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            this.Close();
            Commands.Command.NewDocument(Globals.MainWindow, Globals.MainWindow.mainTabControl,
                tli.FileFullPath);
        }

        private void listOfFile_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            TemplateListItem tli = listOfFile.SelectedItem as TemplateListItem;
            if (tli == null) return;

            //预览
            if (System.IO.File.Exists(tli.FileFullPath) == false)
            {
                MessageBox.Show("发生意外状况，文件不存在，无法预览！", Globals.appName,
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            //System.Drawing.Image fileImg = System.Drawing.Image.FromFile(tli.FileFullPath);
            //using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
            //{
            //    fileImg.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
            //}

            //previewImage.Width = fileImg.Width;
            //previewImage.Height = fileImg.Height;

            previewImage.Source = new BitmapImage(new Uri(tli.FileFullPath));
        }

        private void btnOpenUserTemplateDir_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Process.Start("explorer.exe", $"\"{Globals.pathOfUserTemplateDocuments}\"");
        }

        private void listOfFile_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            btnNewFile_Click(sender, e);
        }
    }

    internal class TemplateListItem : ListBoxItem
    {
        public TemplateListItem(string fileFullPath)
        {
            this.fileFullPath = fileFullPath;

            int lastIndex = fileFullPath.LastIndexOf("\\");
            if (lastIndex > -1)
            {
                fileShortName = fileFullPath.Substring(lastIndex + 1);
            }
            else
            {
                fileShortName = "<..无效文件名..>";
            }

            this.Padding = new Thickness(4, 2, 4, 2);
            this.Content = fileShortName;
        }

        private string fileFullPath;

        public string FileFullPath
        {
            get { return fileFullPath; }
        }

        private string fileShortName;

        public string FileShortName
        {
            get { return fileShortName; }
        }
    }

    internal class TemplateDirItem : TreeViewItem
    {
        public TemplateDirItem(string dirFullPath)
        {
            this.dirFullPath = dirFullPath;

            int lastIndex = dirFullPath.LastIndexOf("\\");
            if (lastIndex > -1)
            {
                dirShortName = dirFullPath.Substring(lastIndex + 1);
            }
            else
            {
                dirShortName = "<..无效目录名..>";
            }

            this.Padding = new Thickness(4, 2, 4, 2);
            this.Header = dirShortName;
        }

        private string dirFullPath;

        public string DirFullPath
        {
            get { return dirFullPath; }
        }

        private string dirShortName;

        public string DirShortName
        {
            get { return dirShortName; }
        }
    }
}
